import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactEcharts from 'echarts-for-react';

import { COLOR_AREA_LIST, COLOR_LIST } from '@/utils/constants';

class EchartsLine extends Component {

  static defaultProps = {
    title: '',
    showType: 'line',
    xDatas: [],
    bArea: false,
    bPercent: false,
    bDashboard: true
  }

  constructor(props) {
    super(props);
    const {title, legends, datas, showType, xDatas, bArea, bPercent, bDashboard} = this.props;
    this.option = this.initOption(title, legends, datas, showType, xDatas, bArea, bPercent, bDashboard);
  }

  initOption = (title, legends, datas, showType='line', xDatas=[], bArea=false, bPercent=false, bDashboard=true) => {
    const series = datas.map((data, idx)=>{
      const node = {
        name: legends[idx],
        type: showType,
        smooth: true,
        data
      };
      if(bArea) {
        node['stack'] = 'Total';
        node['areaStyle'] = {
          color: COLOR_LIST[idx%COLOR_LIST.length],
        };
        node['emphasis'] = {
          focus: 'series'
        }
      }
      if(!bDashboard && showType == 'line' && !bArea) {
        node['itemStyle'] = {
          normal: {
            color: COLOR_LIST[idx%COLOR_LIST.length],
            lineStyle: {
              color: COLOR_LIST[idx%COLOR_LIST.length],
              width: 1,
            },
            areaStyle: {
              color: COLOR_AREA_LIST[idx%COLOR_LIST.length],
            }
          }
        }
      }
      // if(bPercent) {
      //   node['itemStyle'] = {
      //     normal: {
      //       label: {
      //         show: true,
      //         formatter: function (a) {
      //           return a.data + "%";
      //         }
      //       }
      //     }
      //   }
      // }
      return node;
    });
    const option = {
      title: {
        text: title,
        textStyle: {
          color: bDashboard?'white':'black',
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          //   label: {
          //   backgroundColor: '#6a7985'
          // }
        },
        formatter: (params) => {
          let label = [params[0].name];
          params.forEach((item)=>{
            let str = item.seriesName + ': ' + item.value;
            if(bPercent) {
              str +='%';
            }
            label.push(str);
          });
          label = label.join('<br/>');
          return label;
        }
      },
      legend: {
        left: 'center',
        textStyle: {
          color: bDashboard?'white':'black',
        },
        data: [...legends]
      },
      toolbox: {
        feature: {
          magicType: {show: bDashboard, type: ['line', 'bar']},
          saveAsImage: {show: !bDashboard}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: true,//showType == 'bar',
        axisLine: {
          lineStyle: {
            color: bDashboard?'white':'black',
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: bDashboard?'white':'black',
          }
        },
        axisLabel: {
          show: true,
          interval: 'auto',
          formatter: '{value}'+(bPercent?' %':'')
        },
        max: function (value) {
          return bPercent?100:(2*value.max-(value.max+value.min)/2).toFixed(2);
        },
        min: function(value) {
          return bPercent?0:(2*value.min-(value.max+value.min)/2).toFixed(2);
        }
      },
      // dataZoom: [
      //   {
      //     type: 'inside',
      //     start: 0,
      //     end: 10
      //   }
      // ],
      series
    };
    if(xDatas && xDatas.length > 0) {
      option.xAxis.data = xDatas;
    }
    return option;
  };

  updateChart = (legends, datas, showType=null, xDatas=[], bArea, bDashboard) => {
    this.option.series = datas.map((data, idx)=> {
      const node = {
        name: legends[idx],
        type: showType ? showType : this.props.showType,
        smooth: true,
        data,
        connectNulls: true
      }
      if(!bDashboard && showType == 'line' && !bArea) {
        node['itemStyle'] = {
          normal: {
            color: COLOR_LIST[idx%COLOR_LIST.length],
            lineStyle: {
              color: COLOR_LIST[idx%COLOR_LIST.length],
              width: 1,
            },
            areaStyle: {
              color: COLOR_AREA_LIST[idx%COLOR_LIST.length],
            }
          }
        }
      }
      return node;
    });
    this.option.legend.data = [...legends];
    if(xDatas && xDatas.length > 0) {
      this.option.xAxis.data = xDatas;
    }
    if(this.echarts) {
      this.echarts.getEchartsInstance().clear();
      this.echarts.getEchartsInstance().setOption(this.option);
    }
  }

  componentWillUnmount() {
    if(this.echarts) {
      this.echarts.getEchartsInstance().dispose();
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.showType !== this.props.showType || JSON.stringify(nextProps.datas) !== JSON.stringify(this.props.datas)) {
      const { legends, datas, showType, bArea, bDashboard } = nextProps;
      this.updateChart(legends, datas, showType, bArea, bDashboard);
    }
  }

  render() {
    // console.log("render()", this.props);
    return (
      <ReactEcharts
        ref={(e) => { this.echarts = e; }}
        notMerge={true}
        lazyUpdate={true}
        // theme={bDashboard?'dark':'light'}
        option={this.option}
        style={{width:'100%',height:'100%',backgroundColor:'transparent'}}
      />
    );
  }
}

EchartsLine.proTypes = {
  title: PropTypes.string,
  legends: PropTypes.array.isRequired,
  datas: PropTypes.array.isRequired,
  showType: PropTypes.string,
  xDatas: PropTypes.array,
  bArea: PropTypes.bool,
  bPercent: PropTypes.bool,
  bDashboard: PropTypes.bool
}

export default EchartsLine;
